package com.common.library.tools;

import java.security.MessageDigest;

/**
 * @author txf
 * @Title 字符串工具
 * @package com.txf.prevention.tools
 * @date 2017/5/3 0003
 */

public class StringTools {
    /**
     * MD5加密
     * 32位大写
     */
    public static String MD5(String text) {
        String textMD5;
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update((text).getBytes("UTF-8"));
            byte b[] = md5.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0) {
                    i += 256;
                }
                if (i < 16) {
                    buf.append("0");
                }
                buf.append(Integer.toHexString(i));
            }
            textMD5 = buf.toString().toUpperCase();
        } catch (Exception e) {
            return null;
        }
        return textMD5;
    }
    /**
     * 字符串非空验证
     * */
    public static boolean isNull(String text) {
        if (text == null)
            return true;
        if (text.isEmpty())
            return true;
        return false;
    }



    /**
     *字符串解密
     *@param msg 字符串
     *@return String 返回加密字符串
     */
    public static String decrypt(String msg)
    {
        try
        {
            String name = new String();
            java.util.StringTokenizer st=new java.util.StringTokenizer(msg,"%");
            while (st.hasMoreElements()) {
                int asc =  Integer.parseInt((String)st.nextElement()) - 27;
                name = name + (char)asc;
            }

            return name;
        }catch(Exception e)
        {
            e.printStackTrace() ;
            return null;
        }
    }

    /**
     *字符串加密
     *@param msg 字符串
     *@return String 返回加密字符串
     */
    public static String encrypt(String msg)
    {
        try
        {
            byte[] _ssoToken = msg.getBytes("ISO-8859-1");
            String name = new String();
            // char[] _ssoToken = ssoToken.toCharArray();
            for (int i = 0; i < _ssoToken.length; i++) {
                int asc = _ssoToken[i];
                _ssoToken[i] = (byte) (asc + 27);
                name = name + (asc + 27) + "%";
            }
            return name;
        }catch(Exception e)
        {
            e.printStackTrace() ;
            return null;
        }
    }

}
